import axios from 'axios'
import router from '@/router/index'
import {isEmpty} from '@/util/common'
import {responseError} from "@/util/response";
import {getAccessToken} from "@/util/storage/userStorage";
import {clearSessionStorage} from "@/util/storage/storage";

/**
 * 报错处理
 */
const getResponseErrorMessage = (response) => {
  console.log("请求错误做点什么", response);
  if (isEmpty(response)) {
    return responseError('')
  }
  const {status = null, data} = response || {}
  console.log('status', status)
  if (status === 403) {
    return responseError('拒绝访问')
  }
  if (status === 500) {
    return responseError('网络请求错误')
  }
  if (status === 520) {
    return responseError('网络请求错误')
  }
  if (status === 401) {
    return responseError('token异常', status)
  }
  return responseError(data.message || '')
}


console.log('baseURL', import.meta.env.VITE_APP_BASE_API)
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 30000,
  headers: {
    'X-Custom-Header': 'foobar'
  }
})
// 添加请求拦截器
service.interceptors.request.use((config) => {
  // 在发送请求之前做些什么
  const token = getAccessToken()
  // console.log('token',token)
  config = {
    ...config,
    headers: {
      'X-Access-Token': token
    }
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
})

// 添加响应拦截器
service.interceptors.response.use((response) => {
  // 对响应数据做点什么
  console.log('response', response)
  const {config} = response
  if (config.isReturnNativeResponse) {
    return response
  }
  return response.data;
}, function (error) {
  console.log('error.response', error.response)
  // 对响应错误做点什么
  const {response} = error
  const {config, data} = response || {}
  console.log('config', config)
  if (config.isReturnNativeResponseByError) {
    response.myNativeResponseData = getResponseErrorMessage(response)
    return Promise.reject(response);
  }
  console.log('error.response.data', error.response.data)
  if (data.code == 401) {
    // token失效
    clearSessionStorage()
    console.log('router', router)
    router.replace('/')
    console.log('token失效')
  }
  return Promise.reject(response);
})
export default service

